<?php
namespace Admin\Logic;
use Think\Model;
/**
 * Created by PhpStorm.
 * User: sunku
 * Date: 2017/12/19
 * Time: 13:49
 */
class ItemCateLogic extends Model{
    protected $trueTableName = 'wz_item_category';

    public function saveItemCate($params){
        $id = isset($params['id'])? trim($params['id']):0;
        $name = isset($params['name'])? trim($params['name']):0;
        $pid = isset($params['pid'])? intval($params['pid']):0;
        $status = isset($params['status'])? intval($params['status']):1;
        $is_schedule = isset($params['is_schedule'])? intval($params['is_schedule']):1;
        $is_enquiry = isset($params['is_enquiry'])? intval($params['is_enquiry']):1;

        $data = [];
        $name && $data['name'] = $name;
        $data['pid'] = $pid;
        $status && $data['status'] = $status;
        $is_enquiry && $data['is_enquiry'] = $is_enquiry;
        $is_schedule && $data['is_schedule'] = $is_schedule;
        $data['depth'] = 1;
        if(isset($pid) && $pid){
            $cate = D("Resource/ItemCate","Service")->getCateInfo(['id'=>$pid]);
            $data['depth'] = $cate['depth']+1;
        }

        if(!$id){
            $cateInfo = D("Resource/ItemCate","Service")->getCateInfo(['name'=>$name,'status'=>['in',[-1,0,1]],'depth'=>$data['depth'],'pid'=>$pid]);
            if($cateInfo){
               return Response(2003,"该分类已存在");
            }
            $result = D('Resource/ItemCate','Service')->addCate($data);
        }else{
            $data['id'] = $id;
            $result = D('Resource/ItemCate','Service')->UpdateCate($data);
        }
        if(!$result){
            return Response(2001,"操作失败");
        }else{
            return Response(999,"操作成功");
        }
    }

    /**
     * @param $params
     * @return string
     */
    public function deleteItemCate($params){
        $id = isset($params['id'])? trim($params['id']):0;
        $status = isset($params['status'])? intval($params['status']):-5;
        if(!$id){
           return Response(2001,"参数异常");
        }
        $data = [];
        $data['id'] = $id;
        $data['status'] = $status;

        $cate = D("Resource/ItemCate","Service")->getCateInfo(['id'=>$id]);

        if(!$cate){
           return Response(2003,"未查询到该分类信息");
        }
        $cate_son = D("Resource/ItemCate","Service")->getCateInfo(['pid'=>$id,'status'=>['in',[-1,0,1]]]);
        if($cate_son){
           return Response(2002,"请先删除子分类");
        }

        $result = D('Resource/ItemCate','Service')->UpdateCate($data);

        if(!$result){
            return Response(2004,"操作失败");
        }else{
            return Response(999,"操作成功");
        }
    }
}